<?php
/**
 * 管理员登录中间件
 *
 * Author: Zeon
 * Date: 2017/11/20
 * Created by Panxsoft.
 */

namespace App\Http\Middleware;

use App\Exceptions\AdminManageException;
use App\Http\Models\Admin;
use App\Services\AdminErrCode;
use App\Services\Utils\ApiChecker;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\JWTGuard;

class AdminAuth {

    use ApiChecker;

    public static $admin;

    /**
     *
     * @example composer require tymon/jwt-auth@1.0.0-beta.3
     * @link http://jwt-auth.readthedocs.io/en/docs/quick-start/
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws \Exception
     */
    public function handle(Request $request, Closure $next)
    {
        $this->checkToken($request);
    
        /** @var JWTGuard $jwt */
        $jwt = Auth::guard('admin');

        /** @var Admin|null $admin */
        $admin = $jwt->user() ?: null;
        if (! $admin) {
            throw new AdminManageException(AdminErrCode::JWT_TOKEN_NOT_FOUND, 'invalid token');
        }

        self::$admin = $admin;

        return $next($request);
    }
    
    /**
     * @param Request $request
     */
    private function checkToken(Request $request)
    {
        if (config('app.debug_admin')) return;
        
        $token = $request->bearerToken() || $request->token;
    
        $this->checkJwtTokenExist($request);
    }
}